package dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import dao.UserDao;
import domain.User;
import utils.DBUtil;
@Repository("sd")//后加
public class UserDaoImpl implements UserDao {
	@Autowired//后加
	private DataSource ds;//后加.先按类型绑定，如果有两个数据池，按名称绑定，不要用ds1,ds2，用ds sd
	@Override
	public int addUser(User s) {
		int rs = 0;
		String sql = "insert into stu (name,sex,xh,psd,groupid) values(?,?,?,?,?)";
		Connection con = null;//后加
//		Connection con = DBUtil.connect();配置guo-servlet.xml前
		PreparedStatement pst = null;

		try {
			con=ds.getConnection();//后加
			pst = con.prepareStatement(sql);
			pst.setString(1, s.getName());
			pst.setBoolean(2, s.isSex());
			pst.setString(3, s.getXh());
			pst.setString(4, s.getPsd());
			pst.setInt(5, s.getGroupid());
			rs = pst.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			DBUtil.free(con, pst, null);
		}

		return rs;
	}

	@Override
	public User findStu(String xh, String psd) {
		User s = null;
		String sql = "select * from stu where xh=? and psd=?";
		Connection con = DBUtil.connect();
		PreparedStatement pst = null;
		ResultSet rs = null;

		try {
			pst = con.prepareStatement(sql);
			pst.setString(1, xh);
			pst.setString(2, psd);
			rs = pst.executeQuery();
			if (rs.next()) {
				s = new User();
				s.setId(rs.getInt("id"));
				s.setName(rs.getString("name"));
				s.setSex(rs.getBoolean("sex"));
				s.setXh(rs.getString("xh"));
				s.setGroupid(rs.getInt("groupid"));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			DBUtil.free(con, pst, rs);
		}

		return s;
	}

}
